#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试对话ID不匹配问题
检查ChromaDB搜索结果中的conversation_id是否能在MongoDB中找到对应的对话记录
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.config import load_config
from src.database.manager import DatabaseManager

async def debug_conversation_id_mismatch():
    """调试对话ID不匹配问题"""
    print("=== 调试对话ID不匹配问题 ===")
    
    # 加载配置
    config = load_config()
    
    # 初始化数据库管理器
    db_manager = DatabaseManager(config)
    await db_manager.initialize()
    
    try:
        print("\n--- 1. 从ChromaDB搜索对话 ---")
        # 搜索一些对话
        search_results = await db_manager.chromadb_client.search_conversations(
            "王者荣耀", limit=5
        )
        
        print(f"ChromaDB搜索结果数量: {len(search_results)}")
        
        if search_results:
            print("\n--- 2. 检查每个conversation_id ---")
            for i, result in enumerate(search_results[:3]):  # 只检查前3个
                conv_id = result.get('conversation_id')
                message_id = result.get('id')  # ChromaDB中的文档ID
                similarity = result.get('similarity', 0)
                
                print(f"\n结果 {i+1}:")
                print(f"  ChromaDB文档ID: {message_id}")
                print(f"  conversation_id: {conv_id}")
                print(f"  相似度: {similarity:.4f}")
                
                # 尝试从MongoDB获取对话信息
                try:
                    conv_info = await db_manager.mongodb_client.get_conversation(conv_id)
                    if conv_info:
                        print(f"  ✓ MongoDB中找到对话: {conv_info.get('title', 'N/A')}")
                        print(f"    用户ID: {conv_info.get('user_id')}")
                        print(f"    创建时间: {conv_info.get('created_at')}")
                    else:
                        print(f"  ✗ MongoDB中未找到对话")
                        
                        # 尝试按_id查找
                        conv_info_by_id = await db_manager.mongodb_client.get_conversation_by_id(conv_id)
                        if conv_info_by_id:
                            print(f"  ✓ 按_id找到对话: {conv_info_by_id.get('title', 'N/A')}")
                        else:
                            print(f"  ✗ 按_id也未找到对话")
                            
                except Exception as e:
                    print(f"  ✗ 查询MongoDB失败: {e}")
        
        print("\n--- 3. 检查MongoDB中的对话ID格式 ---")
        # 获取MongoDB中的一些对话
        try:
            # 使用正确的方法名
            conversations_collection = db_manager.mongodb_client.db['conversations']
            mongo_conversations = await conversations_collection.find().limit(3).to_list(length=3)
            print(f"MongoDB对话数量: {len(mongo_conversations)}")
            
            for i, conv in enumerate(mongo_conversations):
                print(f"\n对话 {i+1}:")
                print(f"  conversation_id: {conv.get('conversation_id')}")
                print(f"  _id: {conv.get('_id')}")
                print(f"  title: {conv.get('title', 'N/A')}")
        except Exception as e:
            print(f"获取MongoDB对话失败: {e}")
            
        print("\n--- 4. 检查ChromaDB中存储的元数据 ---")
        # 直接查询ChromaDB集合
        try:
            collection = db_manager.chromadb_client.client.get_collection("conversations")
            # 获取前几个文档的元数据
            results = collection.get(limit=3, include=["metadatas", "documents"])
            
            print(f"ChromaDB文档数量: {len(results['ids'])}")
            
            for i, (doc_id, metadata, document) in enumerate(zip(
                results['ids'], results['metadatas'], results['documents']
            )):
                print(f"\n文档 {i+1}:")
                print(f"  文档ID: {doc_id}")
                print(f"  conversation_id: {metadata.get('conversation_id')}")
                print(f"  user_id: {metadata.get('user_id')}")
                print(f"  role: {metadata.get('role')}")
                print(f"  文档内容: {document[:100]}...")
                
        except Exception as e:
            print(f"查询ChromaDB集合失败: {e}")
            
    finally:
        print("\n--- 清理资源 ---")
        await db_manager.close()
        print("数据库连接已关闭")

if __name__ == "__main__":
    asyncio.run(debug_conversation_id_mismatch())